package com.zhangxiaofanfan.hotcode.fourth.third;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-06-26 20:33:33
 */
public class HotCode050 {
    public static void main(String[] args) {

    }

    private Integer maxSum = 0;
    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return maxSum;
        }
        maxSum = root.val;
        bfs(root);
        return maxSum;
    }

    public int bfs(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int left = Math.max(bfs(node.left), 0);
        int right = Math.max(bfs(node.right), 0);
        int curMaxSum = node.val + left + right;
        maxSum = Math.max(curMaxSum, maxSum);
        return node.val + Math.max(left, right);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
